<template> 
  <div class="app-container">
    <el-tabs v-model="activeName" >
      <el-tab-pane label="资料列表" name="first">
        <div style="margin-top: 15px">
          <el-form :inline="true" :model="listQuery" size="mini" label-width="80px">
            <el-form-item label="名称：">
              <el-input v-model="listQuery.fileName" ></el-input>
            </el-form-item>
            <el-form-item label="类型：">
              <el-select v-model="listQuery.typeCode" placeholder="请选择" clearable filterable>
                <el-option
                  v-for="item in codeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="资料分类：">
              <el-select
                clearable
                v-model="listQuery.classId"
                filterable
                remote
                reserve-keyword>
                <el-option
                  v-for="item in classList" :key="item.classId" :value="item.classId" :label="item.className">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品分类：">
              <el-cascader
                clearable
                v-model="selectProductCateValue"
                :options="productCateOptions"
                :props="{value:'categoryId', label:'categoryName',children:'children',emitPath:false}"></el-cascader>
            </el-form-item>
            <el-form-item label="厂家：">
              <el-select class="paramInput" v-model="listQuery.brandId" clearable filterable>
                <el-option
                  v-for="item in bandlist"
                  :key="item.brandId"
                  :label="item.brandName"
                  :value="item.brandId">
                  <span>{{ item.brandName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="牌号：">
              <el-select
                clearable
                v-model="listQuery.goodsSn"
                filterable
                value-key="id"
                remote
                reserve-keyword
                :remote-method="remoteMethod2"
                :loading="loading"
                placeholder="请输入牌号关键词">
                <el-option
                  v-for="(item,index) in goodsSns" :key="item.id"
                  :label="item.goodsSn"
                  :value="item.goodsSn">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                @click="handleSearchList()"
                type="primary">
                查询
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="saveProductLibrary"
                @click="showPop('add','')"
                type="primary">
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table-container">
          <el-table ref="productTable"
                    :data="list"
                    style="width: 100%;font-size: 12px"
                    v-loading="listLoading"
                    border>
            <el-table-column label="品名" align="center" min-width="100">
              <template slot-scope="scope">
                <p>{{scope.row.categoryName}}</p>
              </template>
            </el-table-column>
            <el-table-column label="厂家"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.brandName}}</template>
            </el-table-column>
            <el-table-column label="牌号" min-width="100" align="center">
              <template slot-scope="scope">
                {{scope.row.goodsSn}}
              </template>
            </el-table-column>
            <el-table-column label="资料名称"  align="center" min-width="150">
              <template slot-scope="scope">{{scope.row.fileName}}</template>
            </el-table-column>
            <el-table-column label="分类"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.className}}</template>
            </el-table-column>
            <el-table-column label="类型"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.typeCode | fifCode}}</template>
            </el-table-column>
            <el-table-column label="上传时间"  align="center" min-width="150">
              <template slot-scope="scope">{{scope.row.createTime}}</template>
            </el-table-column>
            <el-table-column label="上传类型"  align="center" min-width="100">
              <template slot-scope="scope">{{scope.row.userTypeName}}</template>
            </el-table-column>
            <el-table-column label="操作"  align="center" fixed="right" min-width="150">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="showPop('edit',scope.row)"  v-if="saveProductLibrary">修改</el-button>
                <el-button type="text" size="mini" @click="handleDelete(scope.row)"  v-if="saveProductLibrary">删除</el-button>
                <el-button type="text" size="mini" @click="toPreview(scope.row)">预览附件</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :page-size="listQuery.pageSize"
            :page-sizes="[10,15,20]"
            :current-page.sync="listQuery.pageNum"
            :total="total">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="分类名称" name="second" v-if="productLibraryClass">
        <div style="margin-top: 15px">
          <el-form :inline="true" :model="listQuery2" size="mini" label-width="80px">
            <el-form-item label="名称：">
              <el-input v-model="listQuery2.keyword" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                @click="handleSearchList2()"
                type="primary">
                查询
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="productLibraryClass"
                @click="showPop2('add','')"
                type="primary">
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table-container">
          <el-table ref="productTable"
                    :data="list2"
                    style="width: 100%;font-size: 12px"
                    v-loading="listLoading2"
                    border>
            <el-table-column label="分类名称" align="center">
              <template slot-scope="scope">
                <p>{{scope.row.className}}</p>
              </template>
            </el-table-column>
            <el-table-column label="排序"  align="center" >
              <template slot-scope="scope">{{scope.row.sortOrder}}</template>
            </el-table-column>

            <el-table-column label="操作"  align="center">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="showPop2('edit',scope.row)" v-if="productLibraryClass">修改</el-button>
                <el-button type="text" size="mini" @click="handleDelete2(scope.row)" v-if="productLibraryClass">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            layout="total, sizes,prev, pager, next,jumper"
            :page-size="listQuery2.pageSize"
            :page-sizes="[10,15,20]"
            :current-page.sync="listQuery2.pageNum"
            :total="total2">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>


    <!--新增修改审核-->
    <el-dialog
      title="资料信息"
      :visible.sync="dialogVisible"
      width="600px">
      <el-form :model="value" :rules="rules" ref="value" label-width="100px" size="small" >
        <el-form-item label="分类/厂家/牌号" prop="categoryId" v-if="popType != 'pass'">
          <el-select
            clearable
            v-model="goodsName"
            filterable
            value-key="id"
            remote
            reserve-keyword
            :remote-method="remoteMethod"
            :loading="loading"
            placeholder="请输入牌号关键词" @change="changeGoodsSn">
            <el-option
              v-for="(item,index) in goodsSnList" :key="index" :value="item" :label="item | fifitem">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="分类/厂家/牌号">
          {{goodsName}}
        </el-form-item>
        <el-form-item label="资料名称" prop="fileName">
          <el-input v-model="value.fileName" style="width:210px;"/>
        </el-form-item>
        <el-form-item label="类型" prop="typeCode">
          <el-radio-group v-model="value.typeCode">
            <el-radio :label="item.code" v-for="(item,index) in codeList" :key="index">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分类" prop="classId" v-if="value.typeCode == 'factory' || value.typeCode == 'third'">
          <el-select
            clearable
            v-model="value.classId"
            filterable
            remote
            reserve-keyword>
            <el-option
              v-for="item in classList" :key="item.classId" :value="item.classId" :label="item.className">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件" prop="fileUrl" ref="imgform">
          <div style="margin-bottom:10px;">
            <el-link type="primary" @click="toPreview(value)" v-if="value.fileUrl != ''">{{value.fileUrl}}</el-link>
          </div>
          <el-upload
            v-if="popType != 'pass'"
            :data="uploadToken"
            action="https://upload.qiniup.com"
            :show-file-list="false"
            :http-request="sliderRequest"
            :before-upload="beforeAvatarUpload"
            :on-error="onError"
            >
            <el-button size="small" type="primary" :loading="upLoading">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg/pdf文件</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
          <div v-if="popType != 'pass'">
               <el-button @click="closedDialog">取 消</el-button>
               <el-button type="primary" @click="onSubmit" :loading="btnLoading">确 定</el-button>
          </div>
          <div v-else>
             <el-button @click="onPass(2)"  :loading="btnLoading3">审核不通过</el-button>
             <el-button type="primary" @click="onPass(1)" :loading="btnLoading2">审核通过</el-button>
        </div>

      </span>
    </el-dialog>


    <!--新增修改分类-->
    <el-dialog
      title="分类信息"
      :visible.sync="dialogVisible2"
      width="600px">
      <el-form :model="value2" :rules="rules2" ref="value2" label-width="100px" size="small">
        <el-form-item label="分类名称" prop="className">
          <el-input v-model="value2.className" style="width:210px;"/>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="value2.sortOrder" :controls="false"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
           <el-button @click="closedDialog2" size="small">取 消</el-button>
           <el-button type="primary" @click="onSubmit2" :loading="btnLoading4"  size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import {documentFileList,documentClassList,getGoodsSnList,fileDel,fileEdit} from '@/api/product'
// import {fetchListWithChildren} from '@/api/productCate'
// import {brandList,goodsSnList} from '@/api/brand'
// import {fileCheck, fileclassAdd, fileClassDel, fileclassList} from "@/api/product";

import{getQiniuToken,fileGoodsSnList} from '@/api/partner'
import{setDocumentFile,delDocumentFile,getDocumentClassList,setDocumentClass,delDocumentClass,getCategoryList,getBrandList,getGoodSnList} from '@/api/product'
import axios from "axios";
import store from '@/store'
import {mapGetters} from "vuex";
const defaultListQuery = {
  "fileName"  : "", //资料名称
  "typeCode"    : '', //资料类型ID
  "categoryId" : '', //商品分类ID
  "brandId"    : '', //品牌ID
  "goodsSn"    : "", //牌号
  fileState:'',
  classId:'',
  "pageNum"    : 1,
  "pageSize"   : 10
};

const defaultListQuery2 = {
  "keyword"  : "", //分类名称
  "pageNum"    : 1,
  "pageSize"   : 10
};
const defaultValue = {
  "fileId"     : 0,  //文件ID，为0表示新增
  "fileName"   : "", //资料名称
  "fileUrl"    : "", //附件地址
  "categoryId" : '',  //商品分类ID
  "brandId"    : '',  //品牌ID
  "goodsSn"    : "",  //牌号
  "classId"    : '',        //资料类型ID
  "typeCode"   : "", //类型(原厂:factory，第三方:third，物流表:properties，其它:other)
   sapGoodsNo:''
};

const defaultValue2 = {
  "classId"   : 0,      //类型ID,为0时表示新增
  "className" : "", //类型名称
  "sortOrder" : 0      //排序值
};
export default {
  name: "updateList",

  data() {
    return {
      listQuery: Object.assign({},defaultListQuery),
      list: null,
      total: null,
      listLoading: true,
      codeList:[
        {code:'factory',name:'原厂资料'},
        {code:'third',name:'第三方'},
        // {code:'properties',name:'物性表'},
        {code:'other',name:'其它资料'},
      ],
      fileStateList:[
        {code:0,name:'待审核'},
        {code:1,name:'已审核'},
        {code:2,name:'审核不通过'},
      ],
      activeName:'first',
      selectProductCateValue: null,
      productCateOptions: [],
      bandlist:[],//商品厂家列表
      goodsSns:[],//商品牌号列表
      options:[],
      dialogVisible:false,
      value:JSON.parse(JSON.stringify(defaultValue)),
      rules:{
        fileName:[{required: true, message: '此项必填', trigger: 'blur'}],
        fileUrl:[{required: true, message: '此项必填', trigger: 'change'}],
        categoryId:[{required: true, message: '此项必填', trigger: 'change'}],
        classId:[{required: true, message: '此项必填', trigger: 'change'}],
        typeCode:[{required: true, message: '此项必填', trigger: 'change'}],
      },
      popType:'',
      goodsSnList:[],
      goodsName:'',
      loading:false,
      classList:[],


      upLoading:false,
      btnLoading:false,
      btnLoading2:false,
      btnLoading3:false,


      listQuery2: Object.assign({},defaultListQuery2),
      list2: null,
      total2: null,
      listLoading2: true,
      btnLoading4:false,

      dialogVisible2:false,
      value2:JSON.parse(JSON.stringify(defaultValue2)),
      rules2:{
        className:[{required: true, message: '此项必填', trigger: 'blur'}],
        sortOrder:[{required: true, message: '此项必填', trigger: 'blur'}],
      },
      uploadToken:{
        token:'',
      },
      imgDomain:'',
      roles:store.getters.roles ? store.getters.roles : [],

    }
  },
  created() {
    this.getList();
    this.getProductCateList();
    this.getGoodsSnList();
    this.getBrandList();
    this.getList2();
    this.getClassList()
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    saveProductLibrary(){
      if(this.roles.indexOf("saveProductLibrary") != -1){
        return true
      }else{
        return false
      }
    },
    productLibraryClass(){
      if(this.roles.indexOf("productLibraryClass") != -1){
        return true
      }else{
        return false
      }
    },
  },
  filters: {
    fifitem(item){
      return item.categoryName+'/'+item.brandName+'/'+item.goodsSn
    },
    fifCode(val){
      if(val == 'factory'){
        return '原厂资料'
      }else if(val == 'third'){
        return '第三方'
      }else if(val == 'properties'){
        return '物性表'
      }else if(val == 'other'){
        return '其它资料'
      }
    },
  },
  watch: {
    selectProductCateValue: function (newValue) {
      let array = newValue;
      console.log(newValue)
      if (array && array.length > 1){
        if (array[0] == array[1]) {
          array.splice(1,1);
        }
      }else if(array && array.length == 0){
        array = null;
      }
      this.listQuery.categoryId = array;
    }
  },

  methods: {
    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },

    onPass(type){
      this.submitPass()
    },


    //删除资料
    handleDelete( row) {
      this.$confirm('确定删除此资料吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delDocumentFile({fileId:row.fileId}).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          });
          this.getList();
        });
      });
    },

    //上传文件重写
    sliderRequest(upload) {
      // 文件上传自行处理上传
      // 创建FormData对象 添加相关上传参数
      const formData = new FormData()
      // 文件对象
      formData.append('file', upload.file)
      // key 文件名处理，这样的话七牛会识别文件时什么类型
      let timestamp=new Date().getTime();
      var result =/\.[^\.]+/.exec(upload.file.name);
      let fileName = timestamp + upload.file.name
      formData.append('key', fileName)
      // token
      formData.append('token', this.uploadToken.token)//这个postData,要在data数据里面进行定义的，，，我这里调接口使用的是vue的方式
      // 上传文件
      // onUploadProgress 查看axios文档 https://github.com/axios/axios
      axios.post("https://upload.qiniup.com", formData, {
        onUploadProgress: (event) => {
          // 监听上传进度
          event.percent = event.loaded / event.total * 100
          upload.onProgress(event)
        }
      }).then((response) => {
        console.log("response",response)
        if (response.status === 200) {
          let res = response.data;
          console.log(this.imgDomain+res.key);
          this.value.fileUrl=this.imgDomain+res.key
          this.upLoading = false;
          this.$message({
            message: '上传成功',
            type: 'success',
            duration: 1000
          });
          this.$refs['imgform'].clearValidate();
        }else{
          this.onError()
        }
      }).catch((err) => {
        // 调用组件上传失败方法
        this.onError()
      })
    },

    beforeAvatarUpload(file) {
      const isIMG = (/^image\/(jpg|jpeg|png)$/.test(file.type) || /^application\/(pdf)$/.test(file.type))
      if (!isIMG) {
        this.$confirm('上传资料只支持JPG,PNG,PDF格式', '提示', {
          confirmButtonText: '知道了',
          showCancelButton: false,
          type: 'error'
        })
      }
      if(isIMG){
        this.upLoading = true
      }
      return isIMG
    },

    /**
     * 上传成功
     * @param res
     * @param file
     */
    handleSuccess(res) {
      this.value.fileUrl=this.imgDomain+res.key
      this.upLoading = false;
      this.$message({
        message: '上传成功',
        type: 'success',
        duration: 1000
      });
      this.$refs['imgform'].clearValidate();
    },
    onError(){
      this.upLoading = false;
      this.$message({
        message: '上传失败',
        type: 'error',
        duration: 1000
      });
    },

    getClassList(){
      getDocumentClassList({pageNum: 1,pageSize: 10000}).then((res)=>{
        this.classList = res.list
      })
    },
    changeGoodsSn(item){
      if(item){
        this.value.categoryId = JSON.parse(JSON.stringify(item.categoryId));
        this.value.categoryName = JSON.parse(JSON.stringify(item.categoryName));
        this.value.brandId = JSON.parse(JSON.stringify(item.brandId));
        this.value.brandName = JSON.parse(JSON.stringify(item.brandName));
        this.value.goodsSn = JSON.parse(JSON.stringify(item.goodsSn));
        this.value.sapGoodsNo = JSON.parse(JSON.stringify(item.sapGoodsNo));
        this.goodsName = item.categoryName+'/'+item.brandName+'/'+item.goodsSn
      }else{
        this.value.categoryId = '';
        this.value.categoryName = '';
        this.value.brandId = '';
        this.value.brandName = '';
        this.value.goodsSn = '';
        this.value.sapGoodsNo = '';
        this.goodsName = '';

      }
    },

    //获取商品列表
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        getGoodSnList({goodsSn:query}).then((res)=>{
          this.goodsSnList = res.list;
          this.loading = false;
        }).catch(()=>{
          this.loading = false;
        });
      } else {
        this.goodsSnList = [];
      }
    },
    //获取商品列表
    remoteMethod2(query) {
      if (query !== '') {
        this.loading = true;
        getGoodSnList({goodsSn:query}).then((res)=>{
          this.goodsSns = res.list;
          this.loading = false;
        }).catch(()=>{
          this.loading = false;
        });
      } else {
        this.goodsSns = [];
      }
    },
    showPop(type,item){
      this.popType = type;
      if(type == 'add'){
        this.value = JSON.parse(JSON.stringify(defaultValue))
      }else{
        this.value = JSON.parse(JSON.stringify(item))
        this.value.classId = this.value.classId == 0 ? '' : this.value.classId
        this.goodsName = item.categoryName+'/'+item.brandName+'/'+item.goodsSn
        this.remoteMethod(item.goodsSn)
      }
      this.dialogVisible = true;
      this.getUploadToken()
      setTimeout(()=>{
        this.$refs['value'].clearValidate();
      },300)
    },
    closedDialog(){
      this.dialogVisible = false;
      this.goodsSnList = [];
      this.goodsName = ''

    },

    //新建修改
    onSubmit(){
      this.$refs['value'].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.value));
          setDocumentFile(data).then(()=>{
            this.$message({
              message: '保存成功',
              type: 'success',
              duration: 1000
            });
            this.btnLoading = false;
            this.getList();
            this.closedDialog();
          }).catch(()=>{
            this.btnLoading = false;
          });

        } else {
          return false;
        }
      });
    },
    toPreview(item){
      window.open(item.fileUrl)
    },

    /**
     *获取分类列表
     **/
    getProductCateList() {
      getCategoryList().then(response => {
        this.productCateOptions = response.list;
      });
    },
    //获取商品品牌列表
    getBrandList() {
      getBrandList().then(response => {
        this.bandlist = response.list;
      }).catch(()=>{
      })
    },


    //获取商品牌号列表
    getGoodsSnList() {
      getGoodSnList().then(response => {
        this.goodsSns = response.list;
      }).catch(()=>{
      })
    },



    /**
     *获取统计列表
     **/
    getList() {
      this.listLoading = true;
      fileGoodsSnList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.list;
        this.total = response.count;
      });
    },

    /**
     * 按条件搜索
     */
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //改变查看页数
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },

    //改变页码
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },


    /**
     *获取分类列表
     **/
    getList2() {
      this.listLoading2 = true;
      getDocumentClassList(this.listQuery2).then(response => {
        this.listLoading2 = false;
        this.list2 = response.list;
        this.total2 = response.count;
      });
    },

    /**
     * 按条件搜索
     */
    handleSearchList2() {
      this.listQuery2.pageNum = 1;
      this.getList2();
    },

    //改变查看页数
    handleSizeChange2(val) {
      this.listQuery2.pageNum = 1;
      this.listQuery2.pageSize = val;
      this.getList2();
    },

    //改变页码
    handleCurrentChange2(val) {
      this.listQuery2.pageNum = val;
      this.getList2();
    },

    //删除分类
    handleDelete2( row) {
      this.$confirm('确定删除此分类吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delDocumentClass({classId:row.classId}).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          });
          this.getList2();
          this.getClassList()
        });
      });
    },


    showPop2(type,item){
      this.popType = type;
      if(type == 'add'){
        this.value2 = JSON.parse(JSON.stringify(defaultValue2))

      }else{
        this.value2 = JSON.parse(JSON.stringify(item))
      }
      this.dialogVisible2 = true;
      setTimeout(()=>{
        this.$refs['value2'].clearValidate();
      },300)
    },
    closedDialog2(){
      this.dialogVisible2 = false;
    },

    //新建修改
    onSubmit2(){
      this.$refs['value2'].validate((valid) => {
        if (valid) {
          this.btnLoading4 = true;
          let data = JSON.parse(JSON.stringify(this.value2));
          setDocumentClass(data).then(()=>{
            this.$message({
              message: '保存成功',
              type: 'success',
              duration: 1000
            });
            this.btnLoading4 = false;
            this.getList2();
            this.closedDialog2();
            this.getClassList()
          }).catch(()=>{
            this.btnLoading4 = false;
          });

        } else {
          return false;
        }
      });
    },


  },

}
</script>
<style scoped lang="scss">
.qr-con{
  text-align: center;
  img{
    width:180px;
    height:180px;
  }
  .text{
    font-size:14px;
    margin-top:10px;
  }
}
.upload-div{
  text-align: center;
  position:relative;
  #upload{
    opacity: 0;
    position: absolute;
    z-index: 1;
    width:154px;
    height:40px
  }
}
</style>


